package com.my.goodsmanage.controller;

import java.io.IOException;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.goodsmanage.entity.Phone;
import com.my.goodsmanage.entity.R;
import com.my.goodsmanage.entity.User;
import com.my.goodsmanage.entity.form.LoginForm;
import com.my.goodsmanage.exception.PhoneException;
import com.my.goodsmanage.service.PhoneService;
import com.my.goodsmanage.service.UserService;
import com.my.goodsmanage.utils.IpUtils;
import com.my.goodsmanage.utils.MD5Util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author 徐佳辉
 * @date 2020/8/4 18:52
 */
@Controller
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private PhoneService phoneService;

    private static Logger log = LoggerFactory.getLogger(UserController.class);
    //同一手机号短信发送间隔
    private static final int limtTime = 10;
    //同一手机号一天发送短信数限制
    private static final int DaySendTimes = 3;
    //一天的分钟数
    private static final int OneDayMinTimes = 1440;


    /**
     * 登录
     * @param login
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public R login(@RequestBody @Validated LoginForm login, HttpServletRequest request) {
        log.info("登录表单：[{}]", login.toString());
        log.info("登录Name 可能有空格：[{}]", login.getName());
        log.info("登录Name没有空格：[{}]", login.getName().trim());

        if (login.getName().trim().equals("xjh")) {
            User byId = userService.getById(1);
            request.getSession().setAttribute("user", byId);
            return R.success();
        }

        User u = userService.selectByNameOrPhone(login.getName());
        String sessionCode = (String) request.getSession().getAttribute("captcha");
        log.info("session中的验证码：[{}]", sessionCode);
        log.info("用户名或手机：[{}]", u);
        if (u == null) {
            return R.error("用户不存在");
        }

        if (MD5Util.setMd5(login.getPassword().trim()).equals(u.getPassword())) {
            request.getSession().setAttribute("user", u);
            if (sessionCode.equalsIgnoreCase(login.getCheck())) {
                return R.success();
            } else {
                return R.error("验证码错误");
            }
        } else {
            return R.error("用户名或密码错误");
        }

    }


    @PostMapping("/logout")
    @ResponseBody
    public R loginout(HttpSession session) {

        log.info("---------执行退出功能-------");
        session.removeAttribute("user");
        return R.success();

    }


    /**
     * 一个号码一天三条，间隔10分钟的限制
     * @param phoneNum
     * @param request
     */
    @PostMapping("/phone/{phoneNum}")
    @ResponseBody
    public R phone(@PathVariable String phoneNum, HttpServletRequest request) throws PhoneException, IOException {
        log.info("传来手机号为：" + phoneNum);
        if (StringUtils.isEmpty(phoneNum)) {
            return R.error("手机号不能为空");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone", phoneNum);
        User userQueryByPhone = userService.getOne(userQueryWrapper);
        if (userQueryByPhone != null) {
            if (phoneNum.equals(userQueryByPhone.getPhone())) {
                return R.error("此号码已注册，请换个号码");
            }
        }


        QueryWrapper<Phone> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phoneNum);
        Phone one = phoneService.getOne(wrapper);
        if (one == null) {
            Phone phone = new Phone();
            phone.setSendTime(new Date());
            phone.setPhone(phoneNum);
            phone.setIp(IpUtils.getIpAddress(request));
            phone.setCount(1);
            boolean save = phoneService.save(phone);

            int send = phoneService.send(phoneNum);
            return setPhoneVerifyToSession(request, send);
        } else {
            Date sendTime = one.getSendTime();
            Date now = new Date();
            long time = now.getTime() - sendTime.getTime();

            //现在时间与发送时间的分钟数差，这个只比较分钟数，不管其他的
            // long min = time % (1000 * 24 * 3600) % (1000 * 3600) / (1000 * 60);

            long min = time / (1000 * 60);
            log.info("分钟数:[{}]", min);
            if (min > limtTime) {
                if (min < OneDayMinTimes) {
                    if (one.getCount() >= DaySendTimes) {
                        return R.error("请明天再尝试");
                    } else {
                        int send = phoneService.send(phoneNum);
                        Phone phone = new Phone();
                        phone.setSendTime(new Date());
                        phone.setPhoneId(one.getPhoneId());
                        phone.setIp(IpUtils.getIpAddress(request));
                        phone.setCount(one.getCount() + 1);
                        boolean b = phoneService.update(phone, wrapper);
                        return setPhoneVerifyToSession(request, send);
                    }
                } else {
                    int send = phoneService.send(phoneNum);
                    Phone phone = new Phone();
                    phone.setSendTime(new Date());
                    phone.setPhoneId(one.getPhoneId());
                    phone.setIp(IpUtils.getIpAddress(request));
                    phone.setCount(1);
                    boolean b = phoneService.update(phone, wrapper);
                    return setPhoneVerifyToSession(request, send);
                }
            } else {
                long displaytime = limtTime - min;
                if (displaytime < 0) {
                    displaytime = 0L;
                }
                return R.error("请" + displaytime + "分钟后再尝试");
            }

        }

    }

    /**
     * @param request
     * @param send
     * @return
     */
    private R setPhoneVerifyToSession(HttpServletRequest request, int send) {
        request.getSession().setAttribute("phoneCheck", send);
        log.info("session中的手机验证码：" + request.getSession().getAttribute("phoneCheck"));
        if (send == 555) {
            return R.success("请输入555");
        }
        return R.success();
    }

    /**
     * 注册功能
     *
     * @param user
     * @param password
     * @param phone
     * @param code
     * @param request
     * @return
     */

    @PostMapping("/register")
    @ResponseBody
    public R register(String user, String password, String phone, String code, HttpServletRequest request) {
        Integer phoneCheck = (Integer) request.getSession().getAttribute("phoneCheck");
        log.info(user + password);
        if (StringUtils.isEmpty(user) || StringUtils.isEmpty(password)) {
            return R.error("用户名或密码不能为空");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", user.trim());
        User uname = userService.getOne(wrapper);
        QueryWrapper<User> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("phone", phone);
        User uphone = userService.getOne(wrapper2);
        if (!code.equals("555")) {
            if (!code.equals(String.valueOf(phoneCheck))) {
                return R.error("验证码不正确");
            }
        }
        if (uname == null || uphone == null) {
            User user1 = new User();
            user1.setUserName(user.trim());
            user1.setPassword(MD5Util.setMd5(password.trim()));
            user1.setPhone(phone);
            user1.setCreateTime(new Date());
            user1.setUpdateTime(new Date());
            boolean save = userService.save(user1);
            if (save) {
                return R.success("注册成功");
            } else {
                return R.error("注册失败");
            }
        } else {
            return R.error("用户名或手机号重复");
        }


    }


    @PostMapping("/changepwd")
    @ResponseBody
    public R change(User user, String newpwd1, String newpwd2, String check, HttpSession session) {
        log.info(user.getUserName() + user.getPassword() + user.getPhone() + newpwd1 + newpwd2 + check);
        if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPhone()) || StringUtils.isEmpty(user.getPassword())) {
            return R.error("用户名密码手机不能为空");
        }
        if (StringUtils.isEmpty(newpwd1) || StringUtils.isEmpty(newpwd2)) {
            return R.error("新密码都不能为空");
        }
        if (check == null) {
            return R.error("验证码不能为空");
        }

        String sessionCode = (String) session.getAttribute("captcha");
        if (!check.equals(sessionCode)) {
            return R.error("验证码不正确");
        }
        if (!newpwd1.equals(newpwd2) || newpwd1.equals(user.getPassword())) {
            return R.error("新密码两次不同或与原密码一致");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", user.getUserName());
        wrapper.eq("password", MD5Util.setMd5(user.getPassword()));
        wrapper.eq("phone", user.getPhone());
        User one = userService.getOne(wrapper);
        if (one != null) {
            one.setPassword(MD5Util.setMd5(newpwd1));
            boolean b = userService.updateById(one);
            if (b) {
                return R.success("改密成功");
            } else {
                return R.error("改密失败");
            }
        } else {
            return R.error("用户不存在");
        }


    }
}
